import axios from 'axios';
import Vue from 'vue';
import store from '@/store';
const config = require('@/variableConfig');
const { baseHost, buyerBaseApi, wechatAppId, aliAppId } = config(
  process.env.MY_ENV
);
const service = axios.create({
  // url = base url + request url
  baseURL:
    process.env.NODE_ENV !== 'production'
      ? buyerBaseApi
      : baseHost + buyerBaseApi,
  headers: {
    'content-type': 'application/json;charset=UTF-8'
  },
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;

    // 2013: 用户微信未绑定手机号 1000: 买单店铺需要用户登录 100: 领红包正在排队
    if (
      +res.code !== 0 &&
      +res.code !== 2031 &&
      +res.code !== 1000 &&
      +res.code !== 100 &&
      res.success !== 'true'
    ) {
      Vue.prototype.$toast(res.msg || 'Error');
      return Promise.reject(res || 'Error');
    } else {
      return res;
    }
  },
  error => {
    if (+error.response.status === 401) {
      if (store.getters.browserEnvironment === 'wechat') {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wechatAppId}&redirect_uri=${encodeURIComponent(
          window.location.href
        )}&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`;
      } else if (store.getters.browserEnvironment === 'alipay') {
        window.location.href = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${aliAppId}&scope=auth_user&redirect_uri=${encodeURIComponent(
          window.location.href
        )}`;
      }
      return;
    }
    Vue.prototype.$toast('错误代码：' + error.response.status);
    console.log('err' + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
